import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:ui' as ui;

import 'package:study_demo/ui/canvas/controller.dart';

class CanvasPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetBuilder<CanvasController>(
        init: CanvasController(),
        builder: (controller) {
          return Scaffold(
            appBar: AppBar(title: Text('Canvas')),
            body: controller.image != null
                ? CustomPaint(
                    painter: MyCustomPainter(controller.image!),
                  )
                : Container(),
          );
        });
  }
}

class MyCustomPainter extends CustomPainter {
  ui.Image image;

  MyCustomPainter(this.image) : super();

  Paint _paint = new Paint()
    ..color = Colors.red
    ..strokeWidth = 5.0
    ..style = PaintingStyle.stroke
    ..isAntiAlias = true;

  @override
  Future<void> paint(Canvas canvas, Size size) async {
    /// 画直线
    canvas.drawLine(Offset(20.0, 20.0), Offset(100.0, 100.0), _paint);

    /// 画圆
    canvas.drawCircle(Offset(150.0, 100.0), 30.0, _paint);

    /// 画椭圆
    _paint.color = Colors.lightGreenAccent;
    canvas.drawOval(
        Rect.fromCenter(center: Offset(250.0, 200.0), width: 100, height: 60),
        _paint);

    /// 画图片
    canvas.drawImage(image, Offset(20.0, 280.0), _paint);

    /// 画点
    _paint.color = Colors.redAccent;
    canvas.drawPoints(

        /// PointMode的枚举类型有三个，points（点），lines（线，隔点连接），polygon（线，相邻连接）
        PointMode.polygon,
        [
          Offset(20.0, 130.0),
          Offset(100.0, 210.0),
          Offset(100.0, 310.0),
          Offset(200.0, 310.0),
          Offset(200.0, 210.0),
          Offset(280.0, 130.0),
          Offset(20.0, 130.0),
        ],
        _paint);

    /// 画爱心
    var width = 200;
    var height = 300;
    Path path = new Path()..moveTo(width / 2, height / 4);
    path.cubicTo((width * 6) / 7, height / 9, (width * 13) / 13,
        (height * 2) / 5, width / 2, (height * 7) / 12);
    canvas.drawPath(path, _paint);

    Path path2 = new Path();
    path2.moveTo(width / 2, height / 4);
    path2.cubicTo(width / 7, height / 9, width / 21, (height * 2) / 5,
        width / 2, (height * 7) / 12);
    canvas.drawPath(path2, _paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
